<template>
  <div>
    <BasicTable @register="registerTable">
      <template
        #tableTitle
        v-if="isShowHeaderAction()"
      >
        <a-button 
          preIcon="ant-design:plus-outlined" type="primary" 
          @click="handleAdd" style="margin-right: 5px"
        >
          新增
        </a-button>

        <a-button type="primary" preIcon="ant-design:edit-outlined" @click="handleOpenGroup"> 功能组 </a-button>

        <a-dropdown v-if="selectedRowKeys.length > 0 && hasPermission('msg:msgNotice:delete')">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="i-ant-design:delete-outlined" />
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="i-mdi:chevron-down" />
          </a-button>
        </a-dropdown>
      </template>
      <template #channelList="{ record }">
        <template v-for="(item, index) in record.channelList" :key="index">
          <div :class="`${prefixCls}-channel`">
            <div :class="`${prefixCls}-channel-item`" @click="handleMsgSetting(record, item)">
              <Icon v-if="item.status == 1" icon="simple-line-icons:check" :class="`${prefixCls}-channel-icon`" />
              <Icon v-else icon="simple-line-icons:check" />
              <span>{{ item.name }}</span>
            </div>
          </div>
        </template>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <MsgNoticeForm @register="registerMsgNoticeForm" @success="reload" showFooter />
    <ConfigChannel @register="registerConfigChannel" @success="reload" />
    <MyDataGroupList @register="registerGroupDrawer" @success="reload" :bizType="DataGroupBizType.MSG_PUSH_TASK" />
    <MsgReceiverList @register="registerMsgReceiverList" />
  </div>
</template>
<script lang="ts" name="msg-notice" setup>
  import { ref } from "vue"
  import { BasicTable, TableAction } from "/@/components/Table"
  import { CheckboxGroup } from "ant-design-vue"
  import { useDrawer } from "/@/components/Drawer"
  import { pageNotice, deleteNotice, batchDeleteNotice, saveOrUpdateGroup, deleteGroup, batchDeleteGroup } from "./api"
  import { columns, searchFormSchema } from "./data"
  import MsgNoticeForm from "./components/MsgNoticeForm.vue"
  import ConfigChannel from "./components/ConfigChannel.vue"
  import MsgReceiverList from "./components/MsgReceiverList.vue"
  import { ReceiverType } from "../receiver/receiver.data"

  import { useMessage } from "/@/hooks/web/useMessage"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { Icon } from "/@/components/Icon"
  import { useUserStore } from "/@/store/modules/user"
  import { useModal } from "/@/components/Modal"
  import { usePermission } from "/@/hooks/web/usePermission"
  import { useDesign } from "/@/hooks/web/useDesign"
  import { useIam } from '/@/hooks/web/useIam'


  import { MyDataGroupList, DataGroupBizType } from "/@/components/BizDataGroup/index"
  const [registerMsgReceiverList, { openDrawer: openMsgReceiverList }] = useDrawer()
  const [registerGroupDrawer, { openDrawer: openGroupDrawer }] = useDrawer()
  const [registerConfigChannel, { openModal: openConfigChannel }] = useModal()
  const { prefixCls } = useDesign("msg-notice")
  const { hasPermission } = usePermission()
  const userStore = useUserStore()
  const [registerMsgNoticeForm, { openDrawer: openMsgNoticeForm }] = useDrawer()
  const { createMessage } = useMessage()

  const { tableContext } = useListPage({
    designScope: "msg-notice",
    tableProps: {
      title: "消息模板列表",
      api: pageNotice,
      bordered: false,
      rowSelectionTipType: "",
      pagination: false,
      showTableSetting: false,
      actionColumn: {
        width: 260,
        title: "操作",
        dataIndex: "action",
        fixed: "right",
        slots: { customRender: "action" },
      },
      columns: columns,
      formConfig: {
        schemas: searchFormSchema,
        fieldMapToTime: [["fieldTime", ["beginDate", "endDate"], "YYYY-MM-DD HH:mm:ss"]],
      },
    },
  })
  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext

  const isShowHeaderAction = () => useIam().isAppHubOrMgt() && (hasPermission('push:SaveMsgGroup') || hasPermission('push:DeleteMsgNotice') || hasPermission('push:SaveMsgNotice'))

  function getTableAction(record) {
    return [
      {
        label: "删除",
        color: "error",
        auth: "msgPush:DeleteMsgNotice",
        ifShow: () => useIam().isAppHubOrMgt(),
        popConfirm: {
          title: `是否确认删除 ${record.name}`,
          confirm: handleDelete.bind(null, record),
        },
      },
      {
        label: "配置渠道",
        ifShow: (e) => useIam().isAppHubOrMgt(),
        onClick: handleOpenConfigChannel.bind(null, record),
      },
      {
        label: useIam().isAppHubOrMgt() ? "编辑" : '查看',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: "接收人",
        ifShow: (e) => record.receiverType === ReceiverType.ADMIN, // 2为管理员
        onClick: handleOpenMsgReceiverList.bind(null, record),
      },
    ]
  }

  const handleMsgSetting = (record, selectedChannel) => {
    console.log("handleMsgSetting", record, selectedChannel)
    openConfigChannel(true, { record, selectedChannel, showEdit: false })
  }

  function getDropDownAction(record): ActionItem[] {
    return [
      
    ]
  }

  function handleAdd() {
    openMsgNoticeForm(true, {
      isUpdate: false,
    })
  }

  function handleEdit(record) {
    openMsgNoticeForm(true, {
      record,
      isUpdate: true,
    })
  }

  async function handleDelete(record) {
    await deleteNotice({ id: record.id }, reload)
  }

  async function batchHandleDelete() {
    await batchDeleteNotice({ ids: selectedRowKeys.value }, reload)
  }

  function handleOpenConfigChannel(record, showEdit = true) {
    if (!record.channelList || record.channelList.length === 0) {
      createMessage.warn("无可用渠道, 请先编辑消息选择可用渠道")
      return
    }
    openConfigChannel(true, { record, showEdit })
  }

  function handleOpenGroup() {
    openGroupDrawer(true, {
      title: "消息功能组",
      width: 800,
      deleteApi: deleteGroup,
      batchDeleteApi: batchDeleteGroup,
      saveOrUpdateApi: saveOrUpdateGroup,
    })
  }

  /**
   * 打开消息接收人列表
   */
  function handleOpenMsgReceiverList(record) {
    openMsgReceiverList(true, { record })
  }

</script>

<style lang="less" scoped>
  @prefix-cls: ~"@{namespace}-msg-notice";

  .@{prefix-cls} {
    &-channel {
      transition: all 0.2s ease;
      div {
        float: left;
        margin-left: 5px;
        cursor: pointer;
        text-align: center;
        vertical-align: middle;

        span {
          text-align: center;
          vertical-align: middle;
          margin-left: 2px;
        }
      }

      div:hover {
        color: @hover-color !important;
        span {
          color: @hover-color !important;
        }
      }

      &-icon {
        color: @hover-color;
      }
    }
  }
</style>
